package com.example.day14_service;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

import java.security.Provider;

/**
 * 安卓四大组件：
 * activity:活动
 * contentprovider:内容提供者：可以进行进程内、进程间数据交互-contentResolver
 * broadcastReceiver:广播接收者：可以进行进程内、进程间交互响应
 * service:服务--长时间在后台运行 不需要UI 执行任务时需要开线程
   intentService：执行耗时任务，不需要开线程，任务结束后会自动结束
 */

public class MainActivity extends AppCompatActivity {
    ServiceConnection connection;
    MyService2.MyBinder binder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS,
                Manifest.permission.READ_SMS,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_CALL_LOG,
                Manifest.permission.READ_CALL_LOG
        },100);

    }

    public void start(View view) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

    public void stop(View view) {
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
    }

    public void bind(View view) {
        Intent intent = new Intent(this, MyService2.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //连接成功
                binder = (MyService2.MyBinder) service;
                binder.play();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                //连接未成功
            }
        };
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }

    public void unbind(View view) {
        if(connection!=null){
            unbindService(connection);
            connection = null;
        }

    }

    public void next(View view) {
        if(connection!=null){
            binder.next();
        }

    }

    public void pre(View view) {
        if(connection!=null){
            binder.pre();
        }

    }
    //使用IntentService实现下载音乐
    public void download(View view) {
        Intent intent = new Intent(this,MyIntentService.class);
        intent.putExtra("path","http://10.161.9.80:8080/res/music/mp3/298317.mp3");//下载的网络路径
        intent.putExtra("file","/sdcard/屋顶.mp3");//下载到本地的文件地址
        startService(intent);
    }
}